import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_preview_page.dart';
import 'package:find_friend/pages/mine/model/followmodel.dart';
import 'package:find_friend/pages/xspace/detail/xdetailpage.dart';
import 'package:find_friend/pages/xspace/model/school_model.dart';
import 'package:find_friend/pages/xspace/school/view/xallscholl_cell.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchResList extends StatefulWidget {
  
  _SearchResListState _state;

  void search(String keyword) {
    _state.search(keyword);
  }
  @override
  _SearchResListState createState() => _state = _SearchResListState();
}

class _SearchResListState extends State<SearchResList> with SingleTickerProviderStateMixin{

  int currTabIndex = 0;
  PageController _pageController;
  TabController _tabController;
  String _keyword = "";
  List<ArticleModel> articleList = [];
  List<FollowModel> userList = [];
  int page = 0;
  RefreshController _refreshController = RefreshController();
  String mineMobile;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);
    _tabController = TabController(length: 2, vsync: this);
    SharedUserInfo.instance().then((value) {
      mineMobile = value.mobile;
      if(mounted) setState(() { });
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  void search(String keyword) {
    _keyword = keyword;
    if(_keyword == "") return;
    _refreshController.requestRefresh();
  }

  _onRefresh() {
    page = 1;
    _request(isrefresh: true);
  }

  _onLoading() {
    page += 1;
    _request();
  }

  _endNormoreData(int perpage) {
    if(perpage < 10) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  _endrefres() {
    if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    if(_refreshController.isLoading) _refreshController.loadComplete();
  }

  void _request({bool isrefresh}) {
    Networktool.request(API.totalsearch, params: {"search": _keyword, "page": page, "rows": 10}, method: NETWORKHTTPMethod.GET, success: (data){
      if(data["data"] != null) {
        final resData = data["data"];

        if(isrefresh) {
          setState(() {
            userList.clear();
            articleList.clear();
          });
        }
        if(resData["userlist"] != null){
          MineFollowListModel m = MineFollowListModel.fromJson(resData["userlist"]);
          _endNormoreData(m.data?.length ?? 0);
          userList.addAll(m.data ?? []);
        }

        if(resData["articlelist"] != null){
          PageModel m = PageModel.fromJson(resData["articlelist"]);
          _endNormoreData(m.data?.length ?? 0);
          articleList.addAll(m.data ?? []);
        }

        // 更新
        setState(() {
          
        });
      }
    },fail: (msg) => AlertTool.showToast(msg),
    finaly: _endrefres());
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(
            height: 30.h,
            margin: EdgeInsets.only(left: 100, right: 100, top: 14),
            child: TabBar(
              controller: _tabController,
              labelColor: APP_main_color,
              indicatorColor: APP_main_color,
              indicatorPadding: EdgeInsets.symmetric(horizontal: 10),
              indicatorWeight: 2,
              onTap: (index){
                setState(() {
                  currTabIndex = index;
                });
                _pageController.animateToPage(index, duration: const Duration(milliseconds: 300), curve: Curves.easeIn);
              },
              tabs: [
                Text("帖子", style: currTabIndex == 0 ? instanceTextStyle(15, APP_font_black, fontWeight: FontWeight.w600) : instanceTextStyle(14, const Color(0xff666666))),
                Text("用户", style: currTabIndex == 1 ? instanceTextStyle(15, APP_font_black, fontWeight: FontWeight.w600) : instanceTextStyle(14, const Color(0xff666666))),
              ],
            ),
          ),
          Container(height: 5, color: APP_scaffold_back_color,),
          Expanded(
            child: PageView(
              controller: _pageController,
              onPageChanged: (index){
                setState(() {
                  currTabIndex = index;
                });
                _tabController.animateTo(index);
              },
              children: [
                // 帖子列表
                Container(
                  color: APP_scaffold_back_color,
                  child: CustomRefreshWidget(
                  controller: _refreshController,
                  onRefresh: _onRefresh,
                  onLoading: _onLoading,
                  page: page,
                    child: articleList.length == 0 ? NodataWidget() : ListView.builder(
                      itemCount: articleList.length,
                      itemBuilder: (context, index){
                        return InkWell(
                          onTap: (){
                            push(context, XDetailPage(model: articleList[index], onRefreshData: _onRefresh));
                          },
                          child: XallSchoolCell(model: articleList[index], isself: mineMobile == articleList[index].mobile,)
                        );
                      }
                    ),
                  ),
                ),
                Container(
                  color: APP_scaffold_back_color,
                  child: CustomRefreshWidget(
                    controller: _refreshController,
                    onRefresh: _onRefresh,
                    onLoading: _onLoading,
                    child: userList.length == 0 ? NodataWidget() : ListView.builder(
                      padding: const EdgeInsets.only(top: 10),
                      itemCount: userList.length,
                      itemBuilder: (context, index){
                        FollowModel m = userList[index];
                        return Column(
                          children: <Widget>[
                            InkWell(
                              onTap: (){
                                push(context, MinePreviewPage(mobile: m.mobile));
                              },
                              child: Container(
                                margin: const EdgeInsets.only(bottom: 10, right: 5, left: 15,),
                                child: Row(
                                  children: [
                                    CustomCircleAvatar(size: 46.h,url: m.avatar),
                                    SizedBox(width: 8.5,),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(m.remarkname ?? "--", style: instanceTextStyle(14, APP_font_black),),
                                        Text(m.bio ?? "--", style: instanceTextStyle(12, APP_font_grey),),
                                      ],
                                    )
                                  ],
                                ),
                              ),
                            )
                          ],
                        );
                      }
                    ),
                  ),
                ),
              ]
            )
          )
        ],
      ),
    );
  }
}


class NodataWidget extends StatelessWidget {
  final String text;

  const NodataWidget({Key key, this.text = "居然什么都没有搜到!"}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset("assets/qque1.png"),
          SizedBox(height: 5,),
          Text(text, style: TextStyle(fontFamily: "cute", fontSize: 18, color: Colors.black),)
        ],
      ),
    );
  }
}